package com.xgc.book.bookserver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xgc.book.bookserver.bean.BookLikeBean;
import com.xgc.book.bookserver.mapper.BookLikeMapper;
import com.xgc.book.bookserver.service.BookLikeService;
import com.xgc.book.bookserver.util.ResultJson;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * <p>
 * 图书收藏表 服务实现类
 * </p>
 *
 * @author wrz
 * @since 2023-11-20
 */
@Service
@Transactional
public class BookLikeServiceImpl extends ServiceImpl<BookLikeMapper, BookLikeBean> implements BookLikeService {
    @Override
    public boolean isLike(int bookId, int vipId) {
        BookLikeBean bookLikeBean = this.getOne(new QueryWrapper<BookLikeBean>().eq("book_id", bookId).eq("vip_id",
                vipId));
        return bookLikeBean != null;
    }

    @Override
    public void updateLike(BookLikeBean bookLikeBean) {
        boolean isLike = isLike(bookLikeBean.getBookId(), bookLikeBean.getVipId());
        if (isLike) {
            this.remove(new QueryWrapper<BookLikeBean>().eq("book_id", bookLikeBean.getBookId()).eq("vip_id",
                    bookLikeBean.getVipId()));
        } else {
            bookLikeBean.setLikeTime(new Date());
            this.save(bookLikeBean);
        }
    }

    @Override
    public ResultJson getPage(int page, int limit, BookLikeBean bookLikeBean) {
        IPage<BookLikeBean> iPage = this.page(new Page<>(page, limit), new QueryWrapper<BookLikeBean>()
                .eq(bookLikeBean.getBookId() != null, "book_id", bookLikeBean.getBookId())
                .eq(bookLikeBean.getVipId() != null, "vip_id", bookLikeBean.getVipId())
                .orderByDesc("like_time"));
        return ResultJson.ok(iPage);
    }
}
